<template>
    <div class="student-index">
        <student-header/>
        <main>
            <div class="left">
                <div class="tools" v-for="tools in toolsArray" @click="tools.click()">
                    <div class="tools-title pointer">
                        <img :src="tools.icon" alt="">
                        <span class="title">{{ tools.title }}</span>
                    </div>
                    <div class="children pointer" v-for="tool in tools.children" @click="tool.click">
                        <img :src="tool.icon" alt="">
                        <span class="title">{{ tool.title }}</span>
                    </div>
                </div>
            </div>
            <div class="right">
                <div class="top">
                    <div class="break pointer" v-show="!!projectName" @click="taskBreak">
                        &lt; 返回
                    </div>
                    <div class="title">
                        {{ projectName ? projectName : "数据采集与处理实训项目" }}
                    </div>
                </div>

                <div class="main">
                    <div class="project pointer" v-for="project in projectArray"
                         @click="openProject({id:project.id,title:project.title})"
                         v-show="!taskArray.length">
                        <img :src="project.image" alt="">
                        <span>{{ project.title }}</span>
                    </div>
                    <n-scrollbar style="max-height: 90vh" v-if="!!taskArray.length">
                        <div class="main" v-show="!!taskArray.length">
                            <div class="task" v-for="task in taskArray" v-show="!!taskArray.length">
                                <h2>{{ task.name }}</h2>
                                <div class="info">
                                    <span>任务内容: </span>
                                    <div style="white-space: pre-wrap">
                                        <n-scrollbar style="max-height: 180px; padding-right: 10px;" trigger="none">
                                            {{ task['task_describe'] }}
                                        </n-scrollbar>
                                    </div>
                                </div>
                                <div class="resources">
                                    <span>
                                        任务资源:
                                    </span>
                                    <a v-for="resources in task.children" :href="resources.url">
                                        {{ resources.name }}
                                    </a>
                                </div>
                                <button class="pointer" @click="enterTask(task.id,task.project_id)">
                                    执行任务
                                </button>

                            </div>
                        </div>
                    </n-scrollbar>
                </div>

            </div>
        </main>
        <flow-popup-window
            :show="popup.show"
            :on-click-outside="popup.clickPopupOutside"
            :x="popup.x"
            :y="popup.y"
        >
            <n-card title="数据库" style="width: 50vw">
                <p>数据库服务器 Server</p>
                <n-input disabled v-model:value="database.server"/>
                <n-input disabled v-model:value="database.database"/>
                <n-input v-model:value="userName" placeholder="用户名"/>
                <n-input v-model:value="passwd" placeholder="密码"/>
                <n-button :disabled="userName!=='root'||passwd!=='123'" @click="connectedDatabase">连接数据库</n-button>
                <p>数据表</p>
                <n-select
                    placeholder="选择数据库中的表"
                    v-model:value="data_source_id"
                    :options="database.children"
                    label-field="name"
                    value-field="id"
                    :disabled="!connectionSuccessful"
                    @update:value="popup.reopen"
                />
                <!--展示文件 已注释-->
                <n-data-table
                    :columns="data.title"
                    :data="data.data"
                    :pagination="pagination"
                    style="height: 300px"
                    flex-height
                    @update:page="updatePage"
                />
                <a ref="dowA" :href="dowUrl" download></a>
                <n-button @click="save">下载数据库表到本地为XLSX</n-button>
            </n-card>
        </flow-popup-window>
        <n-modal v-model:show="showModal">
            <n-card
                style="width: 1200px"
                title="API采集器"
                :bordered="false"
                size="huge"
                role="dialog"
                aria-modal="true"
            >
                <template #header-extra>

                </template>
                <img style="width: 100%;" src="@/assets/student/image/img.png" alt="">
                <template #footer>
                    <n-button @click="saveApi">发送请求并下载响应体</n-button>
                </template>
            </n-card>
        </n-modal>
    </div>
</template>

<script setup>
import StudentHeader from "@/components/header/StudentHeader.vue";
import workApi from "@/http/workApi";
import router from "@/router";
import {NButton, NInput} from "naive-ui";
import FlowPopupWindow from "@/components/VueFlowModel/vueFlowPopupWindow/FlowPopupWindow.vue";
import {STATIC} from "@/assets/server";

const icon = (value) => {
    const val = `${value}-icon`
    return new URL(`/src/assets/student/image/${val}.png`, import.meta.url)
}
const toolsArray = [
    {
        title: "数据采集工具箱",
        icon: icon("tools"),
        click: () => {
        },
        children: [
            {
                title: "网页采集器",
                icon: icon("web"),
                click: () => {
                    let expandScreenUrl = 'gege://'
                    try {
                        console.log(123)
                        window.protocolCheck(expandScreenUrl, function () {
                            window.$dialog.info({
                                title: '监测到未下载网页采集程序',
                                content: '是否进行下载？',
                                positiveText: '下载',
                                negativeText: '算了吧',
                                onPositiveClick: () => {
                                    window.open("/static/download/app/EasySpider_windows_x64.zip")
                                },
                                onNegativeClick: () => {
                                    window.$message.info('说不定有病毒呢是吧? 让我先确定安不安全')
                                }
                            })
                        })
                    } catch (e) {
                        // 捕捉异常
                        console.log(e)
                    }

                },
            },
            {
                title: "API采集器",
                icon: icon("api"),
                click: () => {
                    showModal.value = true
                },
            },
            {
                title: "数据库链接",
                icon: icon("database"),
                click: (e) => {
                    console.log(e)
                    popup.openPopup(e)
                    handleClick2()
                    workApi.get("perform_tasks/get_database", {
                        params: {
                            task_id: "32"
                        }
                    }).then(r => {
                        database.value = r.data
                    })
                },
            },
        ]
    },
    {
        title: "数据处理工作台",
        icon: icon("work"),
        click: () => {
            router.push({name: "Execute"})
        },
    }
]

const projectImageUrl = (value) => {
    const val = `${value}-project`
    return new URL(`/src/assets/student/image/${val}.png`, import.meta.url)
}
const projectArray = [
    {
        title: "Web网页数据爬取与处理",
        image: projectImageUrl("web"),
        id: 32
    },
    {
        title: "表格数据导入与处理",
        image: projectImageUrl("table"),
        id: 35
    },
    {
        title: "数据库抽取与处理",
        image: projectImageUrl("database"),
        id: 33
    },
    {
        title: "API接口对接与处理",
        image: projectImageUrl("api"),
        id: 34
    },
]

const projectName = ref("")
const taskArray = ref([])
const openProject = ({id, title}) => {
    workApi.get("student/task", {
        params: {
            id
        }
    }).then((res) => {
        taskArray.value = res.data
        projectName.value = title
        console.log(taskArray.value)
    })
}
const taskBreak = () => {
    projectName.value = ""
    taskArray.value = []
}
const enterTask = (id, project_id) => {
    router.push({
        name: "Execute",
        query: {
            projectId: project_id,
            taskId: id
        }
    })
}
const mainTitleLeft = computed(() => {
    return projectName.value ? "20px" : "0"
})
const showModal = ref(false)
// 点击弹窗
const popup = reactive({
    show: false,
    x: null,
    y: null,
    clickPopupOutside: () => {
        popup.closedPopup()
    },
    openPopup: (e) => {
        popup.x = e.x
        popup.y = e.y
        popup.show = true
    },
    closedPopup: () => {
        popup.show = false
    },
    reopen: () => {
        popup.show = true
    }
})
const data = ref({
    title: [],
    data: []
})
let markAsRead = false
let isShowNotification = false

function handleClick2() {
    if (!isShowNotification) {
        const n = window.$notification.create({
            title: "连接数据库须知",
            content: `使用该组件可以连接数据库\n加载数据时间与数据库大小成正比, 请耐心等待\n连接用户名:  root\n连接密码:  123`,
            meta: "数据采集与应用分析数智化平台",
            action: () => h(
                NButton,
                {
                    text: true,
                    type: "primary",
                    onClick: () => {
                        // popup.reopen()
                        markAsRead = true
                        n.destroy();
                    }
                },
                {
                    default: () => "已读"
                }
            ),
            onClose: () => {
                popup.reopen()
                if (!markAsRead) {
                    window.$message.warning('请设为已读')
                    return false
                }
            }
        });
        isShowNotification = true
    }
}

let database = ref({
    // server: "https://127.0.0.1:3306",
    server: "https://www.data-acquisition.com/database",
    database: "数据库名称",
    children: []
})
let userName = ref("")
let passwd = ref("")


const connectionSuccessful = ref(false)

function connectedDatabase() {
    window.$message.success("连接成功")
    connectionSuccessful.value = true
}

const data_source_id = ref(null)
watch(data_source_id, (newValue) => {
    workApi.post("perform_tasks/get_database", {
        data_source_id: newValue
    }).then(r => {
        data.value = r.data
    })
})

// 单页数据量
const pagination = {
    pageSize: 10
}

function updatePage() {
    popup.reopen()
}

const dowA = ref(null)
const dowUrl = ref("")

function save() {
    workApi.post("perform_tasks/download_table", {
        data: data.value
    }).then(r => {
        dowUrl.value = r.data.file_url
        console.log(dowA.value)
        setTimeout(() => {
            dowA.value.click()
        }, 1)
    })
}

const saveApi = () => {
    dowUrl.value = STATIC + "download/api/api.json"
    // dowUrl.value = "http://t.weather.itboy.net/api/weather/city/101280601"
    console.log(dowA.value)
    setTimeout(() => {
        dowA.value.click()
    }, 1)
}
</script>

<style scoped lang="less">
.student-index {
    position: relative;
    height: 100vh;
    background-color: #F0F3FB;

    main {
        display: flex;
        height: 90vh;

        .left {
            flex: 15;
            display: flex;
            flex-direction: column;
            align-items: center;

            .tools {
                width: 70%;
                background-color: white;
                margin-bottom: 20%;
                border-radius: 15px;
                padding: 10% 0;

                > div {
                    display: flex;
                    align-items: center;
                    justify-content: space-around;
                    padding: 0 10%;
                    height: 4vh

                }

                //.tools-title {
                //}

                .children {
                    padding-left: 30%;
                }
            }
        }

        .right {
            flex: 85;

            .top {
                display: flex;

                .break {
                    width: 88px;
                    height: 36px;
                    text-align: center;
                    line-height: 36px;
                    border-radius: 10px 10px 10px 10px;
                    color: white;
                    background-color: red;

                }

                .title {
                    position: relative;
                    left: v-bind(mainTitleLeft);
                    width: 216px;
                    height: 48px;
                    text-align: center;
                    line-height: 48px;
                    border-radius: 10px 10px 0 0;
                    background-color: white;
                }
            }


            .main {
                display: flex;
                flex-wrap: wrap;
                //justify-content: center;
                //align-content: flex-start;
                width: 80vw;
                height: 80vh;
                padding: 30px;
                background-color: white;
                //border-radius: 0 20px 20px 20px;
                .project {
                    display: flex;
                    flex-direction: column;
                    align-items: center;
                    width: 603px;
                    max-width: 40%;
                    height: 340px;
                    max-height: 40%;
                    transition: 0.2s;

                    img {
                        width: 556px;
                        max-width: 92%;
                        height: 243px;
                        max-height: 71%;
                    }

                    &:hover {
                        transform: scale(1.102);
                    }
                }

                .task {
                    width: 603px;
                    height: 340px;
                    padding: 10px 50px;
                    margin: 0 10px 20px 10px;
                    background-color: #F7F8FA;
                    position: relative;

                    h2 {
                        position: absolute;
                        top: 25px;
                        left: 27px;
                    }

                    .info {
                        position: absolute;
                        top: 67px;
                        left: 27px;
                    }

                    .resources {
                        position: absolute;
                        top: 280px;
                        left: 27px;

                        a {
                            color: red;
                        }
                    }

                    button {
                        position: absolute;
                        bottom: 25px;
                        left: 40%;
                        width: 160px;
                        height: 40px;
                        color: red;
                        background-color: white;
                    }
                }
            }
        }
    }
}
</style>